//
//  MyLocationLocation.swift
//  MyLocations
//
//  Created by JokerAtBaoFeng on 16/3/17.
//  Copyright © 2016年 baofeng. All rights reserved.
//

import Foundation
import CoreData
import MapKit

@objc(MyLocationLocation)
class MyLocationLocation: NSManagedObject, MKAnnotation {

// Insert code here to add functionality to your managed object subclass
    var coordinate: CLLocationCoordinate2D {
        return CLLocationCoordinate2DMake(latitude, longitude)
    }
    
    var title: String? {
        if locationDescription!.isEmpty {
            return "(No Description)"
        }else {
            return locationDescription
        }
    }
    
    var subtitle: String? {
        return category
    }
    
    
    var hasPhoto: Bool {
        return photoID != nil
    }
    
    var photoPath: String {
        assert(photoID != nil, "No photo ID set")
        let filename = "Photo - \(photoID!.integerValue).jpg"
        return applicationDocumentsDirectory.stringByAppendingPathComponent(filename)
    }
    
    var photoImage: UIImage? {
        return UIImage(contentsOfFile: photoPath)
    }
    
    class func nextPhotoID() -> Int
    {
        let userDefault = NSUserDefaults.standardUserDefaults()
        let currentID = userDefault.integerForKey("photoID")
        userDefault.setInteger(currentID + 1, forKey: "photoID")
        userDefault.synchronize()
        return currentID
    }
    
    func removePhotoFile(){
        if hasPhoto {
            let path = photoPath
            let fileManage = NSFileManager.defaultManager()
            if fileManage.fileExistsAtPath(path) {
                do{
                    try fileManage.removeItemAtPath(path)
                }catch let error as NSError {
                    print("Error remove file: \(error)")
                }
            }
        }
    }
}
